﻿using Application.Common.Interfaces;
using AutoMapper;
using Common.Attributes;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Domain.Entities.Organizations;

namespace Application.Features.Organizations.Commands.Update;

#nullable disable

/// <summary>
/// 修改组织机构
/// </summary>
[Map(typeof(Organization))]
[Description("修改")]
[GroupDescription("组织机构")]
public class UpdateOrganizationCommand : IRequest<bool>
{
    /// <summary>
    /// 唯一标识
    /// </summary>
    [Description("唯一标识")]
    public long OrganizationId { get; set; }

    /// <summary>
    /// 组织机构名称
    /// </summary>
    [Description("组织机构名称")]
    public string? OrganizationName { get; set; }

    /// <summary>
    /// 组织机构负责人
    /// </summary>
    [Description("组织机构负责人")]
    public long? OrganizationPrincipalId { get; set; } = null;

    /// <summary>
    /// 手机号码
    /// </summary>
    [Description("手机号码")]
    public string? PhoneNumber { get; set; }

    /// <summary>
    /// 邮箱
    /// </summary>
    [Description("邮箱")]
    public string? Email { get; set; }


    /// <summary>
    /// 排序
    /// </summary>
    [Description("排序")]
    public int Sort { get; set; }

    /// <summary>
    /// 描述
    /// </summary>
    [Description("描述")]
    public string? Description { get; set; }

    /// <summary>
    /// 状态
    /// </summary>
    [Description("状态")]
    public bool? IsActive { get; set; }

    /// <summary>
    /// 上级节点
    /// </summary>
    [Description("上级节点")]
    public long? ParentId { get; set; } = null;

    /// <summary>
    /// 并发标记
    /// </summary>
    [Required(ErrorMessage = "并发标记必填的")]
    public string ConcurrencyStamp { get; set; }
}

/// <summary>
/// 处理程序
/// </summary>
public class UpdateOrganizationCommandHandler : IRequestHandler<UpdateOrganizationCommand, bool>
{
    private readonly IApplicationDbContext _context;
    private readonly IMapper _mapper;

    public UpdateOrganizationCommandHandler(
        IApplicationDbContext context,
        IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    /// <summary>
    /// 业务逻辑
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <param name="cancellationToken">取消标记</param>
    /// <returns>返回处理结果</returns>
    public async Task<bool> Handle(UpdateOrganizationCommand request, CancellationToken cancellationToken)
    {
        var organization = await _context.Organizations
            .SingleOrDefaultAsync(x => x.Id == request.OrganizationId && x.ConcurrencyStamp == request.ConcurrencyStamp, cancellationToken);

        _mapper.Map(request, organization);
        _context.Organizations.Update(organization);

        return true;
    }
}